package com.gdpu.watermelontimer

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gdpu.watermelontimer.adapter.TaskAdapter
import com.gdpu.watermelontimer.data.PomodoroSession
import com.gdpu.watermelontimer.data.Task
import com.gdpu.watermelontimer.timer.PomodoroTimer
import com.gdpu.watermelontimer.viewmodel.MainViewModel
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import android.widget.RadioGroup
import android.content.Intent
import android.content.SharedPreferences

class MainActivity : AppCompatActivity() {
    
    private lateinit var viewModel: MainViewModel//主界面
    private lateinit var taskAdapter: TaskAdapter//任务适配用的
    // UI组件
    private lateinit var timerText: TextView//倒计时
    private lateinit var timerProgress: ProgressBar//进度
    private lateinit var startButton: Button//开始计时
    private lateinit var pauseButton: Button//暂停
    private lateinit var stopButton: Button//停止
    private lateinit var skipButton: Button//跳过
    private lateinit var todayPomodorosText: TextView//完成倒计时次数
    private lateinit var currentTaskNameInTimer: TextView//任务名
    private lateinit var tasksRecyclerView: RecyclerView//任务控件
    private lateinit var addTaskButton: Button//添加
    private lateinit var settingsButton: Button//设置倒计时
    private lateinit var focusModeButton: Button//专注-待实现
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        
        // 设置窗口边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        initViews()//控件初始化
        initViewModel()//数据&业务逻辑
        setupRecyclerView()
        setupObservers()
        setupClickListeners()

        // 退出登录按钮点击事件
        val logoutText = findViewById<TextView>(R.id.logout_text)
        logoutText.setOnClickListener {
            // 清除本地用户信息
            val prefs = getSharedPreferences("user_prefs", MODE_PRIVATE)
            prefs.edit().clear().apply()
            // 跳转到登录界面
            val intent = Intent(this, LoginActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            startActivity(intent)
        }
        //待实现
        focusModeButton.setOnClickListener {
            focusModeButton.animate()
                .scaleX(20f)
                .scaleY(20f)
                .setDuration(500)
                .withEndAction {
                    val intent = Intent(this, FocusModeActivity::class.java)
                    startActivity(intent)
                    focusModeButton.scaleX = 1f
                    focusModeButton.scaleY = 1f
                }
                .start()
        }
    }
    //绑定控件
    private fun initViews() {
        timerText = findViewById(R.id.timer_text)
        timerProgress = findViewById(R.id.timer_progress)
        startButton = findViewById(R.id.start_button)
        pauseButton = findViewById(R.id.pause_button)
        stopButton = findViewById(R.id.stop_button)
        skipButton = findViewById(R.id.skip_button)
        todayPomodorosText = findViewById(R.id.today_pomodoros_text)
        currentTaskNameInTimer = findViewById(R.id.current_task_name_in_timer)
        tasksRecyclerView = findViewById(R.id.tasks_recycler_view)
        addTaskButton = findViewById(R.id.add_task_button)
        settingsButton = findViewById(R.id.settings_button)
        focusModeButton = findViewById(R.id.focus_mode_button)
    }
    //主界面
    private fun initViewModel() {
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
    }
    //左上角显示的当前任务
    private fun setupRecyclerView() {//左上角显示的当前任务
        taskAdapter = TaskAdapter(
            viewModel = viewModel,
            onTaskStart = { task ->
                viewModel.selectTask(task)
                viewModel.startWorkSession(task.id)
                currentTaskNameInTimer.text = "当前任务：${task.name}"
                Toast.makeText(this, "开始任务: ${task.name}", Toast.LENGTH_SHORT).show()
            },
            onTaskComplete = { task ->
                viewModel.markTaskAsCompleted(task.id)
                Toast.makeText(this, "任务完成: ${task.name}", Toast.LENGTH_SHORT).show()
            },
            onTaskDelete = { task ->
                viewModel.deleteTask(task)
                Toast.makeText(this, "任务已删除", Toast.LENGTH_SHORT).show()
            }
        )
        
        tasksRecyclerView.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)//线性布局任务列表
            adapter = taskAdapter
        }
    }
    //计时器
    private fun setupObservers() {
        // 观察计时器状态
        viewModel.timerState.observe(this) { state ->
            updateTimerUI(state)
        }
        // 观察当前时间
        viewModel.currentTime.observe(this) { time ->
            timerText.text = viewModel.formatTime(time)
        }
        // 观察进度
        viewModel.progress.observe(this) { progress ->
            timerProgress.progress = (progress * 100).toInt()
        }
        // 观察任务列表
        viewModel.tasks.observe(this) { tasks ->
            taskAdapter.updateTasks(tasks)
        }
        // 观察今日西瓜钟数
        viewModel.todayPomodoros.observe(this) { count ->
            todayPomodorosText.text = "今日西瓜钟: $count"
        }
    }

    //按钮点击！
    private fun setupClickListeners() {
        //启动新的任务计时
        startButton.setOnClickListener {
            viewModel.startWorkSession()
        }
        
        pauseButton.setOnClickListener {
            viewModel.pauseTimer()
        }
        
        stopButton.setOnClickListener {
            viewModel.stopTimer()
        }
        
        skipButton.setOnClickListener {
            viewModel.skipSession()
        }
        
        addTaskButton.setOnClickListener {
            showAddTaskDialog()
        }
        
        settingsButton.setOnClickListener {
            showSettingsDialog()
        }
    }
    
    private fun updateTimerUI(state: PomodoroTimer.TimerState) {
        when (state) {
            PomodoroTimer.TimerState.IDLE -> {
                startButton.visibility = View.VISIBLE//显示
                pauseButton.visibility = View.GONE//隐藏
                startButton.text = "开始"
            }
            PomodoroTimer.TimerState.RUNNING -> {
                val currentSession = viewModel.getCurrentSession()
                startButton.visibility = View.GONE
                pauseButton.visibility = View.VISIBLE
            }
            PomodoroTimer.TimerState.PAUSED -> {
                startButton.visibility = View.VISIBLE
                pauseButton.visibility = View.GONE
                startButton.text = "继续"
            }
            PomodoroTimer.TimerState.COMPLETED -> {
                viewModel.saveCurrentSession()
                Toast.makeText(this, "会话完成！", Toast.LENGTH_SHORT).show()
            }
        }
    }
    //添加任务的弹窗
    private fun showAddTaskDialog() {
//        所有控件
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_task, null)
        val nameInput = dialogView.findViewById<TextInputEditText>(R.id.task_name_input)
        val descriptionInput = dialogView.findViewById<TextInputEditText>(R.id.task_description_input)
        val categoryInput = dialogView.findViewById<TextInputEditText>(R.id.task_category_input)
        val estimatedPomodorosInput = dialogView.findViewById<TextInputEditText>(R.id.estimated_pomodoros_input)
        val priorityRadioGroup = dialogView.findViewById<RadioGroup>(R.id.priority_radio_group)
        val btnCancel = dialogView.findViewById<Button>(R.id.btn_cancel)
        val btnSave = dialogView.findViewById<Button>(R.id.btn_save)
//      弹窗！
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
//      取消
        btnCancel.setOnClickListener { dialog.dismiss() }
//      保存
        btnSave.setOnClickListener {
            val name = nameInput.text.toString()
            val description = descriptionInput.text.toString()
            val category = categoryInput.text.toString().ifEmpty { "学习" }
            val estimatedPomodoros = estimatedPomodorosInput.text.toString().toIntOrNull() ?: 1
//          优先级选择
            val priority = when (priorityRadioGroup.checkedRadioButtonId) {
                R.id.priority_important -> Task.Priority.IMPORTANT
                R.id.priority_urgent -> Task.Priority.URGENT
                else -> Task.Priority.ROUTINE
            }
            if (name.isNotEmpty()) {
                viewModel.addTask(name, description, category, priority, estimatedPomodoros)
                Toast.makeText(this, "任务添加成功", Toast.LENGTH_SHORT).show()
                dialog.dismiss()
            } else {
                Toast.makeText(this, "请输入任务名称", Toast.LENGTH_SHORT).show()
            }
        }

        dialog.show()
    }
    //    西瓜钟设置
    private fun showSettingsDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_settings, null)
        val workDurationInput = dialogView.findViewById<TextInputEditText>(R.id.work_duration_input)
        val shortBreakInput = dialogView.findViewById<TextInputEditText>(R.id.short_break_input)
        val longBreakInput = dialogView.findViewById<TextInputEditText>(R.id.long_break_input)
        val longBreakIntervalInput = dialogView.findViewById<TextInputEditText>(R.id.long_break_interval_input)
        
        // 设置西瓜钟默认值
        workDurationInput.setText("25")
        shortBreakInput.setText("5")
        longBreakInput.setText("15")
        longBreakIntervalInput.setText("4")
        
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        
        val btnCancel = dialogView.findViewById<Button>(R.id.btn_cancel)
        val btnSave = dialogView.findViewById<Button>(R.id.btn_save)
        
        btnCancel.setOnClickListener { dialog.dismiss() }
        btnSave.setOnClickListener {
            val workDuration = workDurationInput.text.toString().toIntOrNull() ?: 25
            val shortBreak = shortBreakInput.text.toString().toIntOrNull() ?: 5
            val longBreak = longBreakInput.text.toString().toIntOrNull() ?: 15
            val longBreakInterval = longBreakIntervalInput.text.toString().toIntOrNull() ?: 4
            
            viewModel.updateTimerSettings(
                workDuration * 60 * 1000L,
                shortBreak * 60 * 1000L,
                longBreak * 60 * 1000L,
                longBreakInterval
            )
            
            Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show()
            dialog.dismiss()
        }
        
        dialog.show()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        viewModel.cleanup()
    }
}